package com.gwc.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LogFilter implements Filter {

    private SimpleDateFormat dateFormat =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public LogFilter(){
        System.out.println("LogFilter构造函数");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("LogFilter初始化函数");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        /*
        1、请求到达之前的功能代码
           判断是否登录
           校验权限是否满足
        2、放行代码
        3、返回给浏览器数据之前，所做处理
         */
        // 参数父转子
        HttpServletRequest req =  (HttpServletRequest) servletRequest;
        HttpServletResponse resp =  (HttpServletResponse) servletResponse;

        // 1、请求到达之前的功能代码:输出日志
        String requestURI = req.getRequestURI();
        String date = dateFormat.format(new Date());
        System.out.println(requestURI+"在"+date+"被请求了");

        //2、放行代码,记录执行时间
        long begin = System.currentTimeMillis();
        // 放行
        filterChain.doFilter(req,resp);
        long end = System.currentTimeMillis();

        // 3、返回给浏览器数据之前，所做处理,输出执行时间
        System.out.println(requestURI+"在"+date+"的请求耗时:"+(end-begin)+"毫秒");


    }

    @Override
    public void destroy() {
        System.out.println("LogFilter销毁函数");
    }
}
